from django.shortcuts import render,redirect,HttpResponse

# Create your views here.

from dbadmin import models
import paramiko

def hosts_add(request):
    info = {}
    my_name = request.session.get('username')
    info["my_name"] = my_name
    if request.method == "GET":
        projects_list = models.projects.objects.values()
        hosts_list = models.hosts.objects.values("id","host_name","host_ip","login_type","host_project__p_name","init_status")
        info["projects_list"] = projects_list
        info["hosts_list"] = hosts_list
        return render(request,"hosts_add.html",info)
    else:
        host_name_tmp = request.POST.get("host_name")
        host_ip = request.POST.get("host_ip")
        login_type = request.POST.get("login_type")
        host_project_id = request.POST.get("host_project")
        host_version =  request.POST.get("host_version")
        host_status = models.hosts.objects.filter(host_ip=host_ip).count()
        if host_status == 0:
            project_name = models.projects.objects.filter(id=host_project_id).values("p_name_alias")[0]["p_name_alias"]
            host_name = project_name + host_name_tmp
            models.hosts.objects.create(host_name=host_name,host_ip=host_ip,login_type=login_type,host_version=host_version)
            host_id = models.hosts.objects.filter(host_ip=host_ip).values()[0]["id"]
            obj = models.hosts.objects.get(id=host_id)
            obj.host_project.set([host_project_id])
        else:
            pass
        return redirect("/hosts/add/")

def hosts_del(request):
    if request.method == "GET":
        id = request.GET.get("id")
        models.hosts.objects.filter(id=id).delete()
    else:
        pass
    return redirect("/hosts/add/")

def hosts_init(request):
    if request.method == "GET":
        id = request.GET.get("id")
        host_info = models.hosts.objects.filter(id=id).values("host_project__p_salt__s_version","login_type","host_ip","host_project__p_salt__s_ip","host_name","host_version")[0]
        ssh_info = models.sysconfig.objects.values()[0]
        ssh_key = ssh_info["ssh_key"]

        ssh_user = ssh_info["ssh_user"]
        ssh_port = ssh_info["ssh_port"]
        ssh_pwd = ssh_info["ssh_pwd"]
        f = open("/root/.ssh/id_rsa.pub", mode="r")
        root_key = f.readlines()[0]
        f.close()
        result_info = b""
        if host_info["login_type"] == "1":  #1是密码登录，2是key登录
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname=host_info["host_ip"], port=ssh_port, username=ssh_user, password=ssh_pwd)
            result_info = result_info + bytes("----------yum install salt-repo-latest.XX.noarch.rpm  -y -------\n".encode('utf-8'))
            stdin, stdout, stderr = ssh.exec_command('yum install %s -y' % (host_info["host_project__p_salt__s_version"]))
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            result_info = result_info + bytes("----------yum install salt-minion -y-------\n".encode('utf-8'))

            stdin, stdout, stderr = ssh.exec_command('yum install salt-minion -y')
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            result_info = result_info + bytes("----------ssh_key------\n".encode('utf-8'))
            # stdin, stdout, stderr = ssh.exec_command('echo "%s" >> /root/.ssh/authorized_keys ' % (ssh_key))
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            result_info = result_info + bytes("----------root_key------\n".encode('utf-8'))

            stdin, stdout, stderr = ssh.exec_command('echo "%s" >> /root/.ssh/authorized_keys ' % (root_key))
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            result_info = result_info + bytes("----------minion.cfg update------\n".encode('utf-8'))
            stdin, stdout, stderr = ssh.exec_command(
                "sed -i 's/#master: salt/master: %s/g' /etc/salt/minion" % (host_info["host_project__p_salt__s_ip"]))
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            stdin, stdout, stderr = ssh.exec_command(
                "sed -i 's/#id:/id: %s/g' /etc/salt/minion && echo 'ok'" % (host_info["host_name"]))
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            ssh.close()
            private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')

            # 创建SSH对象
            ssh = paramiko.SSHClient()
            # 允许连接不在know_hosts文件中的主机
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            # 连接服务器
            ssh.connect(hostname=host_info["host_ip"], port=ssh_port, username=ssh_user, pkey=private_key)
            if host_info["host_version"] == "c7":       #根据系统版本启动salt-minion
                ssh.exec_command("systemctl restart salt-minion")
            elif host_info["host_version"] == "c6" or host_info["host_version"] == "u":
                ssh.exec_command("/etc/init.d/salt-minion restart")
            ssh.close()

        else:
            f = open("/tmp/id_rsa", mode="w")
            f.write(ssh_key)
            f.close()
            private_key = paramiko.RSAKey.from_private_key_file('/tmp/id_rsa')

            # 创建SSH对象
            ssh = paramiko.SSHClient()
            # 允许连接不在know_hosts文件中的主机
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            # 连接服务器
            ssh.connect(hostname=host_info["host_ip"], port=ssh_port, username=ssh_user, pkey=private_key)

            # 执行命令

            result_info = result_info + bytes(
                "----------yum install salt-repo-latest.XX.noarch.rpm  -y -------\n".encode('utf-8'))
            stdin, stdout, stderr = ssh.exec_command(
                'yum install %s -y' % (host_info["host_project__p_salt__s_version"]))
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            result_info = result_info + bytes("----------yum install salt-minion -y-------\n".encode('utf-8'))

            stdin, stdout, stderr = ssh.exec_command('yum install salt-minion -y')
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            result_info = result_info + bytes("----------ssh_key------\n".encode('utf-8'))
            # stdin, stdout, stderr = ssh.exec_command('echo "%s" >> /root/.ssh/authorized_keys ' % (ssh_key))
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            result_info = result_info + bytes("----------root_key------\n".encode('utf-8'))

            stdin, stdout, stderr = ssh.exec_command('echo "%s" >> /root/.ssh/authorized_keys ' % (root_key))
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            result_info = result_info + bytes("----------minion.cfg update------\n".encode('utf-8'))
            stdin, stdout, stderr = ssh.exec_command(
                "sed -i 's/#master: salt/master: %s/g' /etc/salt/minion" % (host_info["host_project__p_salt__s_ip"]))
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            stdin, stdout, stderr = ssh.exec_command(
                "sed -i 's/#id:/id: %s/g' /etc/salt/minion && echo 'ok'" % (host_info["host_name"]))
            result_info = result_info + "stdout.read()\n".encode('utf-8') + stdout.read()
            result_info = result_info + "stderr.read()\n".encode('utf-8') + stderr.read()
            ssh.close()

            private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')

            # 创建SSH对象
            ssh = paramiko.SSHClient()
            # 允许连接不在know_hosts文件中的主机
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            # 连接服务器
            ssh.connect(hostname=host_info["host_ip"], port=ssh_port, username=ssh_user, pkey=private_key)
            if host_info["host_version"] == "c7":       #根据系统版本启动salt-minion
                ssh.exec_command("systemctl restart salt-minion")
            elif host_info["host_version"] == "c6" or host_info["host_version"] == "u":
                ssh.exec_command("/etc/init.d/salt-minion restart")
            ssh.close()



    else:
        pass
    models.hosts.objects.filter(id=id).update(init_status=2)    #系统初始化后主机信息状态修改



    t=str(result_info.decode("utf-8"))
    return HttpResponse(t,content_type="html")
